#!/usr/bin/env python3
"""
持久化功能测试运行器
统一运行所有持久化相关的测试
"""
import sys
import os
import unittest
import time
from datetime import datetime

# 添加backend目录到路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'backend'))

def run_all_persistence_tests():
    """运行所有持久化功能测试"""
    print("🚀 AI日志分析引擎 - 持久化功能测试套件")
    print("=" * 60)
    print(f"测试开始时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print("=" * 60)
    
    test_results = {}
    total_start_time = time.time()
    
    # 测试模块列表
    test_modules = [
        {
            'name': '数据库和模型测试',
            'module': 'test_persistence_system',
            'function': 'run_persistence_tests'
        },
        {
            'name': 'API接口测试',
            'module': 'test_workspace_api',
            'function': 'run_api_tests'
        },
        {
            'name': '数据迁移测试',
            'module': 'test_data_migration',
            'function': 'run_migration_tests'
        },
        {
            'name': '前端集成测试',
            'module': 'test_frontend_integration',
            'function': 'run_frontend_tests'
        }
    ]
    
    # 运行每个测试模块
    for test_info in test_modules:
        print(f"\n📋 开始运行: {test_info['name']}")
        print("-" * 40)
        
        start_time = time.time()
        
        try:
            # 动态导入测试模块
            module = __import__(test_info['module'])
            test_function = getattr(module, test_info['function'])
            
            # 运行测试
            success = test_function()
            
            end_time = time.time()
            duration = end_time - start_time
            
            test_results[test_info['name']] = {
                'success': success,
                'duration': duration,
                'error': None
            }
            
            status = "✅ 通过" if success else "❌ 失败"
            print(f"结果: {status} (耗时: {duration:.2f}秒)")
            
        except ImportError as e:
            print(f"⚠️  跳过测试 - 模块导入失败: {e}")
            test_results[test_info['name']] = {
                'success': None,
                'duration': 0,
                'error': f"模块导入失败: {e}"
            }
            
        except Exception as e:
            end_time = time.time()
            duration = end_time - start_time
            
            print(f"❌ 测试执行失败: {e}")
            test_results[test_info['name']] = {
                'success': False,
                'duration': duration,
                'error': str(e)
            }
        
        print("-" * 40)
    
    # 生成测试报告
    total_end_time = time.time()
    total_duration = total_end_time - total_start_time
    
    print("\n" + "=" * 60)
    print("📊 测试结果汇总")
    print("=" * 60)
    
    passed_tests = 0
    failed_tests = 0
    skipped_tests = 0
    
    for test_name, result in test_results.items():
        if result['success'] is True:
            status = "✅ 通过"
            passed_tests += 1
        elif result['success'] is False:
            status = "❌ 失败"
            failed_tests += 1
        else:
            status = "⚠️  跳过"
            skipped_tests += 1
        
        duration_str = f"{result['duration']:.2f}s" if result['duration'] > 0 else "N/A"
        print(f"{test_name:<25} {status:<8} ({duration_str})")
        
        if result['error']:
            print(f"  错误信息: {result['error']}")
    
    print("-" * 60)
    print(f"总计: {len(test_results)} 个测试模块")
    print(f"通过: {passed_tests} | 失败: {failed_tests} | 跳过: {skipped_tests}")
    print(f"总耗时: {total_duration:.2f} 秒")
    print(f"测试结束时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    
    # 生成详细报告
    generate_detailed_report(test_results, total_duration)
    
    # 返回整体测试结果
    return failed_tests == 0

def generate_detailed_report(test_results, total_duration):
    """生成详细的测试报告"""
    report_file = f"test_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.md"
    
    try:
        with open(report_file, 'w', encoding='utf-8') as f:
            f.write("# AI日志分析引擎 - 持久化功能测试报告\n\n")
            f.write(f"**生成时间**: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n")
            f.write(f"**总耗时**: {total_duration:.2f} 秒\n\n")
            
            f.write("## 测试结果概览\n\n")
            f.write("| 测试模块 | 状态 | 耗时 | 备注 |\n")
            f.write("|---------|------|------|------|\n")
            
            for test_name, result in test_results.items():
                if result['success'] is True:
                    status = "✅ 通过"
                elif result['success'] is False:
                    status = "❌ 失败"
                else:
                    status = "⚠️ 跳过"
                
                duration = f"{result['duration']:.2f}s" if result['duration'] > 0 else "N/A"
                error = result['error'] if result['error'] else "-"
                
                f.write(f"| {test_name} | {status} | {duration} | {error} |\n")
            
            f.write("\n## 测试模块详情\n\n")
            
            f.write("### 1. 数据库和模型测试\n")
            f.write("- 测试数据库表创建\n")
            f.write("- 测试工作区CRUD操作\n")
            f.write("- 测试分析会话管理\n")
            f.write("- 测试对话历史管理\n")
            f.write("- 测试数据关系和完整性\n")
            f.write("- 测试UUID处理\n\n")
            
            f.write("### 2. API接口测试\n")
            f.write("- 测试工作区管理API\n")
            f.write("- 测试分析会话API\n")
            f.write("- 测试对话历史API\n")
            f.write("- 测试错误处理和验证\n")
            f.write("- 测试CORS头部\n\n")
            
            f.write("### 3. 数据迁移测试\n")
            f.write("- 测试旧版本数据导入\n")
            f.write("- 测试批量数据迁移\n")
            f.write("- 测试配置数据迁移\n")
            f.write("- 测试迁移后数据完整性\n\n")
            
            f.write("### 4. 前端集成测试\n")
            f.write("- 测试页面加载和导航\n")
            f.write("- 测试工作区管理界面\n")
            f.write("- 测试会话列表显示\n")
            f.write("- 测试响应式设计\n")
            f.write("- 测试错误处理显示\n\n")
            
            f.write("## 环境要求\n\n")
            f.write("- Python 3.7+\n")
            f.write("- SQLAlchemy 2.0+\n")
            f.write("- Flask 2.3+\n")
            f.write("- Chrome浏览器 + ChromeDriver (前端测试)\n")
            f.write("- 前端服务运行在 http://localhost:5173 (前端测试)\n")
            f.write("- 后端服务运行在 http://localhost:8080 (API测试)\n\n")
            
            f.write("## 建议\n\n")
            f.write("1. 在CI/CD流程中定期运行这些测试\n")
            f.write("2. 在发布新版本前必须确保所有测试通过\n")
            f.write("3. 前端集成测试需要浏览器环境，可在开发环境中单独运行\n")
            f.write("4. 数据迁移测试帮助确保版本升级的兼容性\n")
        
        print(f"\n📄 详细测试报告已生成: {report_file}")
        
    except Exception as e:
        print(f"⚠️  生成测试报告失败: {e}")

def print_test_environment_info():
    """打印测试环境信息"""
    print("\n🔧 测试环境信息:")
    print("-" * 30)
    print(f"Python版本: {sys.version}")
    print(f"工作目录: {os.getcwd()}")
    
    # 检查关键依赖
    dependencies = [
        'sqlalchemy',
        'flask',
        'requests',
        'selenium'
    ]
    
    for dep in dependencies:
        try:
            module = __import__(dep)
            version = getattr(module, '__version__', 'Unknown')
            print(f"{dep}: {version}")
        except ImportError:
            print(f"{dep}: 未安装")
    
    print("-" * 30)

if __name__ == '__main__':
    # 打印环境信息
    print_test_environment_info()
    
    # 运行所有测试
    success = run_all_persistence_tests()
    
    if success:
        print("\n🎉 所有测试通过！持久化功能工作正常。")
        exit(0)
    else:
        print("\n❌ 部分测试失败，请检查错误信息。")
        exit(1)
